//
//  XS_FavoriteSubVC.swift
//  XueDao
//
//  Created by fandongtongxue on 2020/12/9.
//

import UIKit

public enum XS_FavoriteSubVCType {
    case course
    case fast_learn
    case interaction
}

class XS_FavoriteSubVC: XS_BaseVC {
    
    public var type : XS_FavoriteSubVCType = .course
    
    var nav : UINavigationController?
    
    var dataArray : [XS_BaseModel] = []
    lazy var courseDataModel = XS_CourseItemM()
    lazy var fastLearnDataModel = XS_FastLearnItemM()

    @IBOutlet weak var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        collectionView.register(UINib.init(nibName: "XS_CourseItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_CourseItemCell")
        collectionView.register(UINib.init(nibName: "XS_FastLearnItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_FastLearnItemCell")
        collectionView.register(UINib.init(nibName: "XS_InteractionItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_InteractionItemCell")
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(headerRefresh))
        collectionView.mj_footer = MJRefreshBackNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(footerRefresh))
        collectionView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: .bottomHeight, right: 0)
        headerRefresh()
    }
    
    @objc func headerRefresh(){
        requestData(isFirst: true)
    }
    
    @objc func footerRefresh(){
        requestData(isFirst: false)
    }
    
    func requestData(isFirst : Bool){
        //        /curriculum/queryUserCollectCurriculum 课程
        //        /quick/queryUserCollectQuickLearn 快学
        var api = "/curriculum/queryUserCollectCurriculum"
        if type == .fast_learn {
            api = "/quick/queryUserCollectQuickLearn"
        }
        if type == .course {
            if isFirst {
                courseDataModel.current = 0
                courseDataModel.records.removeAll()
            }
            XS_NetWork.requestJson(api, parameters: ["pageNo" : courseDataModel.current+1, "pageSize" : courseDataModel.size])
                .mapModel(type: XS_CourseItemM.self) // 返回 模型数组 和原始数据
                .subscribe(onNext: { [weak self] model, resp in
                    guard let `self` = self, resp.success, let model = model else {return }
                    model.records = self.courseDataModel.records + model.records
                    if model.records.count > 0 {
                        XD_BlankPageView.hiddenBlankPageView(superView: self.collectionView)
                        self.courseDataModel = model
                        self.collectionView.reloadData()
                    } else {
                        XD_BlankPageView.blankPage(superView: self.collectionView, imgName: "缺省页_暂无收藏", detailStr: "暂无收藏~", btnTitle: "去首页看看", bottomDetailStr: "") {
                            if let tbc = XS_NVC.shared.viewControllers.first as? XS_TBC {
                                tbc.selectedIndex = 0
                            }
                            self.nav?.popToRootViewController(animated: true)
                        }
                    }
                    self.collectionView.mj_header?.endRefreshing()
                    if model.current >= model.pages { // 没有更多
                        self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        self.collectionView.mj_footer?.endRefreshing()
                    }
                }).disposed(by: disposeBag)
        }else if type == .fast_learn{
            if isFirst {
                fastLearnDataModel.current = 0
                fastLearnDataModel.records.removeAll()
            }
            XS_NetWork.requestJson(api, parameters: ["pageNo" : fastLearnDataModel.current+1, "pageSize" : fastLearnDataModel.size])
                .mapModel(type: XS_FastLearnItemM.self) // 返回 模型数组 和原始数据
                .subscribe(onNext: { [weak self] model, resp in
                    guard let `self` = self, resp.success, let model = model else { return }
                    model.records = self.fastLearnDataModel.records + model.records
                    if model.records.count > 0 {
                        XD_BlankPageView.hiddenBlankPageView(superView: self.collectionView)
                        self.fastLearnDataModel = model
                        self.collectionView.reloadData()
                    } else {
                        XD_BlankPageView.blankPage(superView: self.collectionView, imgName: "缺省页_暂无收藏", detailStr: "暂无收藏~", btnTitle: "去首页看看", bottomDetailStr: "") {
                            if let tbc = XS_NVC.shared.viewControllers.first as? XS_TBC {
                                tbc.selectedIndex = 0
                            }
                            self.nav?.popToRootViewController(animated: true)
                        }
                    }
                    self.collectionView.mj_header?.endRefreshing()
                    if model.current >= model.pages { // 没有更多
                        self.collectionView.mj_footer?.endRefreshingWithNoMoreData()
                    }else{
                        self.collectionView.mj_footer?.endRefreshing()
                    }
                }).disposed(by: disposeBag)
        }
    }

}

extension XS_FavoriteSubVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if type == .course {
            return courseDataModel.records.count
        }else if type == .fast_learn{
            return fastLearnDataModel.records.count
        }
        return 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        if type == .course {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_CourseItemCell", for: indexPath) as! XS_CourseItemCell
            cell.model = courseDataModel.records[indexPath.item]
            return cell
        }else if type == .fast_learn{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_FastLearnItemCell", for: indexPath) as! XS_FastLearnItemCell
            cell.model = fastLearnDataModel.records[indexPath.item]
            cell.delegate = self
            return cell
        }else if type == .interaction{
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_InteractionItemCell", for: indexPath)
            return cell
        }
        return UICollectionViewCell.init()
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        if type == .course {
            return CGSize.init(width: .screenWidth - 32, height: 96)
        }else if type == .fast_learn{
            return CGSize.init(width: floor((CGFloat.screenWidth - 45) / 2), height: 295)
        }else if type == .interaction{
            return CGSize.init(width: .screenWidth, height: 278)
        }
        return CGSize.init(width: 0, height: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 15
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 15, left: 15, bottom: 15, right: 15)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if type == .course {
            let type = courseDataModel.records[indexPath.item].curriculumType
            let id = courseDataModel.records[indexPath.item].id
            if type == "online" {
                //线上课
                let vc = XS_KeChengVC()
                vc.id = id
                nav?.pushViewController(vc, animated: true)
            }else if type == "offline"{
                //线下课
                let vc = XS_KCXianxiaVC()
                vc.id = id
                nav?.pushViewController(vc, animated: true)
            }else if type == "live"{
                //直播课
                let vc = XS_KCZhiboVC()
                vc.id = id
                nav?.pushViewController(vc, animated: true)
            }
        }else if type == .fast_learn{
            let fastDetailVC = XS_KuaiXueDetailVC()
            fastDetailVC.id = fastLearnDataModel.records[indexPath.item].id
            nav?.pushViewController(fastDetailVC, animated: true)
        }
    }
}

extension XS_FavoriteSubVC : XS_FastLearnItemCellDelegate{
    func fastLearnItemCell(fastLearnItemCell: XS_FastLearnItemCell, didClickFavoriteBtn: UIButton) {
        XS_NetWork.requestJson("/collection/collectionCancel",parameters: ["relation":fastLearnItemCell.model.id,"type":"quick"])
            .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                if resp.success{
                    self.headerRefresh()
                }else{
                    self.view.makeToast(resp.msg)
                }
            }).disposed(by: disposeBag)
    }
}
